﻿using System;
using Validate.Net.Core;

namespace Validate.Net.Internals
{
    /// <summary>
    /// 字符串属性长度只能在区间
    /// </summary>
    public class StringLengthAttribute : ValidateBaseAttribute
    {
        /// <summary>
        /// 字符串属性长度只能在区间
        /// <param name="internalPrompts">内联提示语</param>
        /// </summary>
        public StringLengthAttribute(string internalPrompts = null) : base(internalPrompts) { }
        /// <summary>
        /// 区间下界，包括下界。
        /// <see cref="int"/> 或者 <see cref="RangeValue.Infinity"/> 类型的值
        /// </summary>
        public object MinLength { get; set; } = RangeValue.Infinity;

        /// <summary>
        /// 区间上界，包括上界。
        /// <see cref="int"/> 或者 <see cref="RangeValue.Infinity"/> 类型的值
        /// </summary>
        public object MaxLength { get; set; } = RangeValue.Infinity;

        public override string Prompts => string.Format(Properties.Resources.StringLengthPrompts, MinLength.ToString("-"), MaxLength.ToString("+"));

        public override bool OnCheck(object value)
        {
            if (value == null) { return false; }

            if (value is string str)
            {
                if (MinLength is RangeValue.Infinity && MaxLength is RangeValue.Infinity) { return true; }
                else if (MinLength is RangeValue.Infinity && MaxLength is int maxLength)
                { return str.Length <= maxLength; }
                else if ((MaxLength is RangeValue.Infinity && MinLength is int minxLength))
                { return str.Length >= minxLength; }
                else
                {
                    if (MinLength is int min && MaxLength is int max)
                    { return str.Length >= min && str.Length <= max; }
                    else
                    { throw new ArgumentException($"属性 {nameof(MinLength)} 和 {nameof(MaxLength)} 只能是 {nameof(Int32)} 类型的值"); }
                }
            }
            else
            { throw new ArgumentException($"特性 {nameof(StringLengthAttribute)} 只能修饰 {nameof(String)} 类型的属性"); }
        }
    }
}
